<template>
  <div id="userProfileView">
    <a-button type="text" @click="goHome" class="back-btn">
      <icon-arrow-left /> 返回主页
    </a-button>

    <div class="profile-layout">
      <!-- 左侧个人信息区域 -->
      <div class="profile-sidebar">
        <div class="user-basic-info">
          <div class="avatar-container">
            <a-avatar :size="90" shape="circle">
              <img alt="头像" :src="userInfo?.userAvatar" />
            </a-avatar>
          </div>
          <h2 class="user-name">{{ userInfo.userName || '未设置昵称' }}</h2>


          <a-button class="edit-profile-btn" type="outline" @click="showEditForm = true">
            <icon-edit /> 编辑个人资料
          </a-button>
        </div>

        <div class="profile-section">
          <h3 class="section-label">个人简介</h3>
          <p class="profile-text">{{ userInfo.userProfile || '这个用户很懒，还没有填写个人简介' }}</p>
        </div>

        <div class="profile-section">
          <h3 class="section-label">技术栈</h3>
          <div class="tech-tags">
            <a-tag v-for="(tag, index) in userTags" :key="index" size="small" color="blue">{{ tag }}</a-tag>
          </div>
        </div>

        <div class="profile-section">
          <h3 class="section-label">其他信息</h3>
          <div class="info-item">
            <icon-user /> 普通用户
          </div>
          <div class="info-item">
            <icon-calendar /> 注册于 {{ formattedCreateTime }}
          </div>
        </div>
      </div>

      <!-- 右侧主内容区域 -->
      <div class="profile-main">
        <!-- 顶部数据统计卡片 -->
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-icon solved">
              <icon-check-circle />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ userStats.solved || 23 }}</div>
              <div class="stat-label">已解题目</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon submissions">
              <icon-file />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ userStats.submissions || 47 }}</div>
              <div class="stat-label">提交次数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon streak">
              <icon-fire />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ userStats.streak || 5 }}</div>
              <div class="stat-label">连续天数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon pass-rate">
              <icon-thumb-up />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ acceptanceRate }}%</div>
              <div class="stat-label">通过率</div>
            </div>
          </div>
        </div>

        <!-- 活跃度热力图 -->
        <div class="activity-section">
          <div class="section-header">
            <div class="section-title">
              <icon-calendar />
              <span>过去一年共提交 {{ yearTotalSubmissions || 158 }} 次</span>
            </div>
            <a-dropdown trigger="click">
              <a-button size="small" type="text">
                过去一年 <icon-down />
              </a-button>
              <template #content>
                <a-doption>过去一年</a-doption>
                <a-doption>过去6个月</a-doption>
                <a-doption>过去3个月</a-doption>
              </template>
            </a-dropdown>
          </div>
          <div class="heatmap-container">
            <div class="heatmap-grid">
              <div v-for="month in 12" :key="'month-'+month" class="heatmap-month">
                <div v-for="week in 4" :key="'week-'+week" class="heatmap-week">
                  <div v-for="day in 7" :key="'day-'+day" 
                      class="heatmap-cell"
                      :class="getRandomHeatmapClass()">
                  </div>
                </div>
              </div>
            </div>
            <div class="month-labels">
              <span v-for="(month, index) in months" :key="index">{{ month }}</span>
            </div>
          </div>
        </div>

        <!-- 最近提交 -->
        <div class="submissions-section">
          <div class="section-header">
            <div><icon-history /> 最近提交</div>
            <a-link @click="viewAllSubmissions">查看更多记录</a-link>
          </div>
          <a-table
            :data="recentSubmissions"
            :bordered="false"
            :pagination="false"
            size="small"
            :row-class="getRowClass"
          >
            <template #columns>
              <a-table-column title="题目" data-index="questionName">
                <template #cell="{ record }">
                  <a-link @click="viewQuestion(record.questionId)">{{ record.questionName }}</a-link>
                </template>
              </a-table-column>
              <a-table-column title="结果" data-index="status" align="center">
                <template #cell="{ record }">
                  <div class="status-tag" :class="getStatusClass(record.status)">
                    {{ getSubmissionStatusText(record.status) }}
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="语言" data-index="language" align="center">
                <template #cell="{ record }">
                  {{ record.language }}
                </template>
              </a-table-column>
              <a-table-column title="提交时间" data-index="createTime" align="right">
                <template #cell="{ record }">
                  {{ formatTime(record.createTime) }}
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>
    </div>

    <!-- 编辑信息弹窗 -->
    <a-modal
      v-model:visible="showEditForm"
      title="编辑个人资料"
      @ok="handleSave"
      @cancel="showEditForm = false"
      :ok-button-props="{ loading: submitting }"
    >
      <a-form
        :model="userInfo"
        ref="userForm"
        label-align="right"
        :auto-label-width="true"
      >
        <a-form-item field="userName" label="用户名称" required>
          <a-input v-model="userInfo.userName" placeholder="请输入用户名称" />
        </a-form-item>
        <a-form-item field="userProfile" label="个人简介">
          <a-textarea
            v-model="userInfo.userProfile"
            placeholder="请输入个人简介"
            :max-length="200"
            show-word-limit
          />
        </a-form-item>
        <a-form-item field="userTags" label="技术标签">
          <a-input-tag
            v-model="userTags"
            placeholder="添加技术标签，按Enter确认"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import { UserControllerService, QuestionControllerService } from "../../../generated";
import { User, UserUpdateMyRequest } from "../../../generated";
import { 
  IconUser, 
  IconArrowLeft, 
  IconCalendar, 
  IconEdit, 
  IconFire, 
  IconHistory,
  IconCheckCircle,
  IconFile,
  IconThumbUp
} from "@arco-design/web-vue/es/icon";
import { useRouter } from "vue-router";

const userForm = ref();
const userInfo = ref<User>({} as User);
const submitting = ref(false);
const router = useRouter();
const showEditForm = ref(false);
const userTags = ref<string[]>([]);

// 关注统计
const followStats = ref({
  following: 0,
  followers: 0
});

// 用户统计数据
const userStats = ref({
  solved: 23,
  submissions: 47,
  streak: 5
});

// 模拟最近提交记录
interface SubmissionRecord {
  id: string;
  questionId: string;
  questionName: string;
  status: number;
  language: string;
  createTime: number;
}

const recentSubmissions = ref<SubmissionRecord[]>([]);

// 模拟难度分布
const difficulties = ref({
  easy: 15,
  medium: 8,
  hard: 3
});

// 计算通过率
const acceptanceRate = computed(() => {
  if (userStats.value.submissions === 0) return 0;
  // 根据难度分布计算通过数量
  const solvedCount = difficulties.value.easy + difficulties.value.medium + difficulties.value.hard;
  return Math.round((solvedCount / userStats.value.submissions) * 100);
});

// 月份标签
const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

// 年度总提交次数
const yearTotalSubmissions = ref(158);

// 格式化创建时间
const formattedCreateTime = computed(() => {
  if (userInfo.value?.createTime) {
    return moment(userInfo.value.createTime).format("YYYY-MM-DD");
  }
  return "";
});

/**
 * 获取用户角色文本
 */
const getUserRoleText = (role: string): string => {
  switch (role) {
    case 'admin':
      return '管理员';
    case 'user':
      return '普通用户';
    default:
      return '未知角色';
  }
};

/**
 * 生成随机热力图单元格类
 */
const getRandomHeatmapClass = (): string => {
  const random = Math.random();
  if (random < 0.6) return 'heat-level-0';
  if (random < 0.75) return 'heat-level-1';
  if (random < 0.85) return 'heat-level-2';
  if (random < 0.95) return 'heat-level-3';
  return 'heat-level-4';
};

/**
 * 获取提交状态颜色
 */
const getStatusClass = (status: number): string => {
  switch (status) {
    case 2: // 提交成功
      return 'status-success';
    case 3: // 提交失败
      return 'status-fail';
    case 1: // 判题中
      return 'status-judging';
    default: // 等待判题
      return 'status-waiting';
  }
};

/**
 * 获取提交状态文本
 */
const getSubmissionStatusText = (status: number): string => {
  switch (status) {
    case 2: // 提交成功
      return '通过';
    case 3: // 提交失败
      return '答案错误';
    case 1: // 判题中
      return '判题中';
    default: // 等待判题
      return '等待中';
  }
};

/**
 * 获取行样式
 */
const getRowClass = (_record: any, index: number): string => {
  return index % 2 === 0 ? 'even-row' : 'odd-row';
};

/**
 * 格式化时间
 */
const formatTime = (time: number): string => {
  return moment(time).format('YYYY-MM-DD HH:mm');
};

/**
 * 获取当前登录用户信息
 */
const loadUserInfo = async () => {
  try {
    const res = await UserControllerService.getLoginUserUsingGet();
    if (res.code === 0 && res.data) {
      userInfo.value = res.data;
      // 模拟加载技术标签
      userTags.value = ['Java', 'Python', 'JavaScript', 'Vue', 'Spring Boot'];
      // 模拟关注统计
      followStats.value = {
        following: 7,
        followers: 3
      };
      // 加载用户提交统计
      await loadUserSubmitStats();
      // 加载用户最近提交记录
      await loadRecentSubmissions();
    } else {
      message.error("获取用户信息失败：" + res.message);
    }
  } catch (error) {
    message.error("请求出错：" + error);
  }
};

/**
 * 加载用户提交统计
 */
const loadUserSubmitStats = async () => {
  try {
    // 模拟数据已经在上面定义
  } catch (error) {
    console.error("加载用户提交统计失败：", error);
  }
};

/**
 * 加载用户最近提交记录
 */
const loadRecentSubmissions = async () => {
  try {
    // 模拟数据
    recentSubmissions.value = [
      {
        id: '1001',
        questionId: '101',
        questionName: '两数之和',
        status: 2,
        language: 'Java',
        createTime: new Date().getTime() - 24 * 60 * 60 * 1000
      },
      {
        id: '1002',
        questionId: '102',
        questionName: '三数之和',
        status: 3,
        language: 'Python',
        createTime: new Date().getTime() - 2 * 24 * 60 * 60 * 1000
      },
      {
        id: '1003',
        questionId: '103',
        questionName: '合并两个有序链表',
        status: 2,
        language: 'C++',
        createTime: new Date().getTime() - 3 * 24 * 60 * 60 * 1000
      },
      {
        id: '1004',
        questionId: '104',
        questionName: '最长回文子串',
        status: 3,
        language: 'JavaScript',
        createTime: new Date().getTime() - 4 * 24 * 60 * 60 * 1000
      },
      {
        id: '1005',
        questionId: '105',
        questionName: '轮转数组',
        status: 1,
        language: 'Java',
        createTime: new Date().getTime() - 5 * 24 * 60 * 60 * 1000
      }
    ];
  } catch (error) {
    console.error("加载用户最近提交记录失败：", error);
  }
};

/**
 * 返回主页
 */
const goHome = () => {
  router.push("/home");
};

/**
 * 保存用户信息
 */
const handleSave = async () => {
  submitting.value = true;

  const updateData: UserUpdateMyRequest = {
    userName: userInfo.value.userName,
    userProfile: userInfo.value.userProfile,
    // 技术标签数据需要在后端支持，这里暂时不传递
  };

  try {
    const res = await UserControllerService.updateMyUserUsingPost(updateData);
    if (res.code === 0) {
      message.success("个人信息更新成功");
      showEditForm.value = false;
      // 重新加载用户信息
      await loadUserInfo();
    } else {
      message.error("更新失败：" + res.message);
    }
  } catch (error) {
    message.error("请求出错：" + error);
  } finally {
    submitting.value = false;
  }
};

/**
 * 查看全部提交记录
 */
const viewAllSubmissions = () => {
  router.push("/question_submit");
};

/**
 * 查看题目详情
 */
const viewQuestion = (questionId: string) => {
  router.push(`/view/question/${questionId}`);
};

/**
 * 页面加载时获取用户信息
 */
onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
#userProfileView {
  max-width: 1100px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f9fc;
  min-height: 100vh;
}

.back-btn {
  margin-bottom: 20px;
  color: #1890ff;
  font-size: 14px;
}

.profile-layout {
  display: flex;
  gap: 20px;
}

/* 左侧边栏样式 */
.profile-sidebar {
  width: 240px;
  flex-shrink: 0;
}

.user-basic-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  text-align: center;
  margin-bottom: 16px;
}

.avatar-container {
  margin-bottom: 12px;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 12px;
  color: #333;
}

.user-follow-stats {
  display: flex;
  justify-content: center;
  margin: 16px 0;
  align-items: center;
}

.follow-item {
  text-align: center;
  flex: 1;
}

.follow-divider {
  width: 1px;
  height: 24px;
  background-color: #eee;
}

.follow-count {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.follow-label {
  color: #666;
  font-size: 12px;
  margin-top: 2px;
}

.edit-profile-btn {
  width: 100%;
  margin-top: 12px;
  color: #1890ff;
  border-color: #1890ff;
}

.profile-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

.section-label {
  font-size: 14px;
  font-weight: 600;
  margin: 0 0 10px;
  color: #333;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

.profile-text {
  color: #666;
  font-size: 13px;
  line-height: 1.5;
  margin: 0;
  word-break: break-word;
}

.tech-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.info-item {
  margin-bottom: 8px;
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 右侧内容区域样式 */
.profile-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 顶部统计卡片 */
.stats-cards {
  display: flex;
  gap: 12px;
  margin-bottom: 4px;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.solved {
  background-color: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.submissions {
  background-color: rgba(24, 144, 255, 0.1);
  color: #1890ff;
}

.streak {
  background-color: rgba(250, 140, 22, 0.1);
  color: #fa8c16;
}

.pass-rate {
  background-color: rgba(114, 46, 209, 0.1);
  color: #722ed1;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  line-height: 1.2;
}

.stat-label {
  color: #666;
  font-size: 12px;
}

/* 活跃度热力图 */
.activity-section {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  color: #333;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
}

.heatmap-container {
  width: 100%;
  padding: 10px 0;
}

.heatmap-grid {
  display: flex;
  gap: 3px;
  margin-bottom: 12px;
}

.heatmap-month {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 1;
}

.heatmap-week {
  display: flex;
  gap: 2px;
}

.heatmap-cell {
  width: 10px;
  height: 10px;
  border-radius: 2px;
  background-color: #ebedf0;
}

.heat-level-0 {
  background-color: #ebedf0;
}

.heat-level-1 {
  background-color: #9be9a8;
}

.heat-level-2 {
  background-color: #40c463;
}

.heat-level-3 {
  background-color: #30a14e;
}

.heat-level-4 {
  background-color: #216e39;
}

.month-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  padding: 0 10px;
  margin-top: 4px;
}

/* 最近提交记录 */
.submissions-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

:deep(.arco-table-th) {
  background-color: #f9fafc;
  font-weight: 500;
  color: #333;
  font-size: 13px;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.arco-table-td) {
  padding: 10px;
  font-size: 13px;
  color: #333;
  border-bottom: 1px solid #f9fafc;
}

:deep(.even-row) {
  background-color: #fff;
}

:deep(.odd-row) {
  background-color: #f9fafc;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-success {
  background-color: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.status-fail {
  background-color: rgba(245, 34, 45, 0.1);
  color: #f5222d;
}

.status-judging {
  background-color: rgba(24, 144, 255, 0.1);
  color: #1890ff;
}

.status-waiting {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
}

/* 响应式调整 */
@media (max-width: 900px) {
  .profile-layout {
    flex-direction: column;
  }
  
  .profile-sidebar {
    width: 100%;
  }
  
  .stats-cards {
    flex-wrap: wrap;
  }
  
  .stat-card {
    min-width: calc(50% - 6px);
  }
}
</style>
